package cd.zhixuan.utils;

import android.util.Log;

import androidx.annotation.IntRange;
import androidx.annotation.Nullable;

/**
 * 日志打印
 *
 * @author HuZhiChao
 * Create Time: 2021.12.31
 **/
public class LogTools {
    private static final Class<?> THIS_CLASS = LogTools.class;
    /**
     * 调试模式
     */
    private static boolean DEBUG = true;

    public static void setDebug(boolean debug) {
        DEBUG = debug;
    }

    public static boolean isDebug() {
        return DEBUG;
    }

    public static void v(String text) {
        log(0, text);
    }

    public static void d(String text) {
        log(1, text);
    }

    public static void i(String text) {
        log(2, text);
    }

    public static void w(String text) {
        log(3, text);
    }

    public static void e(String text) {
        log(4, text);
    }

    private static void log(@IntRange(from = 0, to = 4) int assist, String text) {
        if (!DEBUG) return;
        if (text == null) return;
        StackTraceElement ste = getStackTraceElement();
        String tag;
        if (ste == null) {
            tag = "unknown";
        } else {
            tag = ste.getClassName() + "::" + ste.getMethodName() + " " + ste.getLineNumber();
        }
        switch (assist) {
            case 0:
                Log.v(tag, text);
                break;
            case 1:
                Log.d(tag, text);
                break;
            case 2:
                Log.i(tag, text);
                break;
            case 3:
                Log.w(tag, text);
                break;
            case 4:
                Log.e(tag, text);
                break;
        }
    }

    @Nullable
    public static StackTraceElement getStackTraceElement() {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();
        for (StackTraceElement st : sts) {
            if (st.isNativeMethod()) {
                continue;
            }
            if (st.getClassName().equals(Thread.class.getName())) {
                continue;
            }
            if (st.getClassName().equals(THIS_CLASS.getName())) {
                continue;
            }
            return st;
        }
        return null;
    }
}
